const app = getApp();
import * as API_Members from '../../api/members'
import * as API_Goods from '../../api/goods.js'
import * as API_Trade from '../../api/trade.js'
import { Foundation } from '../../ui-utils/index.js'
let util = require('../../utils/util.js')

Page({
  data: {
    typeId: 0,
    goods_id:0,
    shop_id:0,
    goodsList:[],
    confirmGoods:true,
    params_goods:{
      page_no: 1,
      page_size: 10
    },
    shopsList:[],
    confirmShops: true,
    params_shops: {
      page_no: 1,
      page_size: 10
    },
    finished_goods: false,//是否加载完成
    finished_shops: false,//是否加载完成
    scrollHeight: '',
    scrollTop: 0,//滚动高度
    showGoTop: false,//显示返回顶部按钮
    pageCount: 0,
    buyNum:1,//加入购物车的数量
    allChecked:false
  },

  getCollection(){ 
    if (this.data.typeId === 0){
      API_Members.getGoodsCollection(this.data.params_goods).then(res => {
        let _pageCount = Math.ceil(res.data_total / this.data.params_goods.page_size)
        this.setData({ pageCount: _pageCount })
        const data = res.data
        if (data && data.length) {
          data.forEach(key => {
            key.goods_price = Foundation.formatPrice(key.goods_price)
          })
          this.setData({ goodsList: this.data.goodsList.concat(data) })
        } else {
          this.setData({ finished_goods: true })
        }
      }).catch(() => {  })
    }else{
      API_Members.getShopCollection(this.data.params_shops).then(res => {
        let _pageCount = Math.ceil(res.data_total / this.data.params_shops.page_size)
        this.setData({ pageCount: _pageCount })
        const data = res.data
        if (data && data.length) {
          this.setData({ shopsList: this.data.shopsList.concat(data) })
        } else {
          this.setData({ finished_shops: true })
        }
      }).catch(() => {  })
    }
  },
  deleteGoodsColl: function(e){
    this.setData({
      confirmGoods: false,
      goods_id: e.currentTarget.dataset.goods_id
    })
  },
  deleteShopColl: util.throttle(function(e){
    this.setData({
      confirmShops: false,
      shop_id: e.currentTarget.dataset.shop_id
    })
  }),
  //取消
  cloneDialog: function () {
    this.setData({
      confirmGoods: true,
      confirmShops: true
    })
  },
  confirmGoods: util.throttle(function(){
    let that = this;
    const goods_id = that.data.goods_id;
    API_Members.deleteGoodsCollection(goods_id).then(()=>{
      wx.showToast({title: '删除成功！' })
      that.setData({
        'params_goods.page_no':1,
        goodsList:[],
        confirmGoods:true
      })
      that.getCollection()
    })
  }),
  confirmShops: util.throttle(function () {
    let that = this;
    const shop_id = that.data.shop_id;
    API_Members.deleteShopCollection(shop_id).then(() => {
      wx.showToast({ title: '删除成功！'})
      that.setData({
        'params_shops.page_no': 1,
        shopsList: [],
        confirmShops: true
      })
      that.getCollection()
    })
  }),
  //单项删除
  deleteGood(e){
    let that=this;
    let goods_id=e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content:'确定要删除此商品？',
      success(res){
        if(res.confirm){
          API_Members.deleteGoodsCollection(goods_id).then(()=>{
            wx.showToast({
              title: '删除成功',
            })
            that.setData({
              'params_goods.page_no':1,
              goodsList:[],
              confirmGoods:true
            })  
            that.getCollection()
          })
        }
      }
    })
  },
  //批量删除
  deleteGoods(){
    let that=this;
    const goods_ids=that.data.goodsList.filter(item=>item.checked).map(item=>item.goods_id)
    console.log(goods_ids)
    wx.showModal({
      title: '提示',
      content:'确定要删除这些商品？',
      success(res){
        if(res.confirm){
          API_Members.deleteGoodsCollections(goods_ids).then(()=>{
            wx.showToast({
              title: '删除成功',
            })
            that.setData({
              'params_goods.page_no':1,
              goodsList:[],
              confirmGoods:true
            })  
            that.getCollection()
          })
        }
      }
    })
  },
  //清空
  clearAll(){
    let that = this;
    wx.showModal({
      title:'提示',
      content:'确定要清空所有店铺吗？',
      success(res){
        if(res.confirm){
          const shop_ids=that.data.shopsList.map(item=>item.shop_id)
          shop_ids.map(e=>{
            API_Members.deleteShopCollection(e).then(() => {
              wx.showToast({ title: '删除成功！'})
              that.setData({
                'params_shops.page_no': 1,
                shopsList: [],
                confirmShops: true
              })   
            })
          })
          that.getCollection()
        }else{
          return
        }
      }
    })
  },
  onLoad: function (options) {
    this.setData({ scrollHeight: wx.getSystemInfoSync().windowHeight - 42 })
    if(options.type!="undefined"){
      let type=Number(options.type)
      this.setData({
        typeId: type
      })
    }
    this.getCollection()
  }, 
  switchTab(event) {
    let index = parseInt(event.currentTarget.dataset.index);
    if (index === 0 && index !== this.data.typeId){
      this.setData({
        'params_goods.page_no': 1,
        goodsList: [],
        typeId: index,
        finished_goods:false,
        pageCount:0
      })
      this.getCollection()
    }
    if (index === 1 && index !== this.data.typeId) {
      this.setData({
        'params_shops.page_no': 1,
        shopsList: [],
        typeId: index,
        finished_shops: false,
        pageCount: 0
      })
      this.getCollection()
    }
  },

  loadMore: function () {
    if (!this.data.finshed) {
      if (this.data.typeId === 0) {
        this.setData({ "params_goods.page_no": this.data.params_goods.page_no += 1 })
        if (this.data.pageCount >= this.data.params_goods.page_no) {
          this.getCollection()
        }
      } else {
        this.setData({ 'params_shops.page_no': this.data.params_shops.page_no += 1 })
        if (this.data.pageCount >= this.data.params_shops.page_no) {
          this.getCollection()
        }
      }
    }
  },
  scroll: function (e) {
    if (e.detail.scrollTop > 200) {
      this.setData({ showGoTop: true })
    } else {
      this.setData({ showGoTop: false })
    }
  },
  //返回顶部
  goTop: function () { this.setData({ scrollTop: 0 }) },
  //加入购物车
  /** 加入购物车 */
  handleAddToCart(e) {
    //console.log(e, 1477777)
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      return false
    }
    const {
      buyNum
    } = this.data
    let id = e.currentTarget.dataset.id;
    API_Goods.getGoodsSkus(id).then(data => {
      // console.log(response);
      let sku_id = data[0].sku_id;
      // console.log(sku_id);
      API_Trade.addToCart(sku_id, buyNum, '').then(response => {
        //更新购物车数量
        wx.showModal({
          title: '提示',
          content: '加入购物车成功，要去看看么？',
          confirmColor: '#f42424',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/cart/cart'
              })
            }
          }
        })
      });
    });
  },
  //批量加入购物车
  addCart(){
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      return false
    }
    const {
      buyNum
    } = this.data
    const goods_ids=this.data.goodsList.filter(item=>item.checked).map(item=>item.goods_id)
    goods_ids.map(e=>{
      API_Goods.getGoodsSkus(e).then(data => {
        // console.log(response);
        let sku_id = data[0].sku_id;
        // console.log(sku_id);
        API_Trade.addToCart(sku_id, buyNum, '').then(response => {
          //更新购物车数量
          wx.showModal({
            title: '提示',
            content: '加入购物车成功，要去看看么？',
            confirmColor: '#f42424',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/cart/cart'
                })
              }
            }
          })
        });
      });
    })
  },
  //单选
  check(e){
    let item=e.currentTarget.dataset.item
    this.data.goodsList.map(key=>{
      if(item.goods_id==key.goods_id){
        key.checked=!key.checked
      }
    })
    this.setData({goodsList:this.data.goodsList})
  },
  //全选
  allCheck(){
    if(this.data.allChecked==false){
      this.data.goodsList.forEach(key=>{
        key.checked=1
      })
      this.setData({allChecked:true,goodsList:this.data.goodsList})
    }
    else{
      this.data.goodsList.forEach(key=>{
        key.checked=0
      })
      this.setData({allChecked:false,goodsList:this.data.goodsList})
    }
  }
})